class ProcessTask < ActiveRecord::Base

  # 获取节点信息，本类属于用户任务，必然会获取到userTask节点
  def node
    @node ||= self.process_active_instance.node if self.process_active_instance_id
  end

  # 完成本次任务
  # :parameters: 参数
  # :variables: 活动变量
  def finish!(parameters={}, variables={})
    # 保存业务变量
    save_variables variables
    self.update_attributes end_at: Time.now, status: 0
    self.process_active_instance.finish!(parameters)
  end


  # 获取引擎中的视图配置
  def view_configs
    node.view_config
  end

  # 用户任务指定的URL
  def show_url
    view_configs[:showUrl] if view_configs
  end

  # 委派人类型标题
  def assignee_type_title
    types = %w(个人 角色 组织 所有人 权限)
    types[self.assignee_type.to_i]
  end

  # 状态标题
  def status_title
    statuses = %w(完成 启动 暂停 异常)
    statuses[self.status]
  end

  private

  # 保存业务变量
  def save_variables(variables)
    transaction do
      variables.each do |key, value|
        var_save key, value
      end
    end
  end

  # 单个业务变量判断类型并存储
  def var_save(key, value)
    process_variable = self.process_instance.process_variables.find_by variable_key: key
    if process_variable.present?
      process_variable.updated_task_id = self.id
    else
      process_variable= ProcessVariable.new variable_key: key, process_instance_id: self.process_instance.id, created_task_id: self.id
    end

    case value.class.name
      when 'String'
        process_variable.variable_type = 0
        process_variable.value_string = value
      when 'Fixnum'
        process_variable.variable_type = 1
        process_variable.value_number = value
      when 'FalseClass', 'TrueClass'
        process_variable.variable_type = 2
        process_variable.value_boolean = value
      else
        process_variable.variable_type = 3
        process_variable.value_file = value.to_s.bytes
    end
    process_variable.save
  end
end
